package com.gexin.core.web;

import com.gexin.common.WebConst;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.model.PageAlert;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.interceptor.SystemAuthInterceptor;
import com.gexin.model.system.AdminLog;
import com.gexin.model.system.AdminLog.Log_Type;
import com.gexin.model.system.AdminUser;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;

/**
 * 系统管理员的 基本控制器
 * 
 * @author 肖得明 20151128
 */
// 拦截用户登陆
@Before(SystemAuthInterceptor.class)
public class SystemBaseController extends Controller {

	/**
	 * 添加日志到
	 * 
	 * @param type
	 * @param infor
	 */
	@NotAction
	public void addLog(Log_Type type, String infor) {
		AdminLog.dao.addLog(type, getLoginUserId(), infor);
	}
	@NotAction
	public void addLog(Log_Type type, String infor, String data) {
		AdminLog.dao.addLog(type, getLoginUserId(), infor, data);
	}

	/**
	 * 获取当前登录的用户 id
	 * 
	 * @return
	 */
	@NotAction
	public Integer getLoginUserId() {
		return getSessionAttr(WebConst.Session_SysUserId);
	}
	@NotAction
	public String getResIdByCookie() {
		return "common_id";
	}

	/**
	 * 
	 * @param title
	 *            操作的标题
	 * @param msg
	 *            提示的信息
	 * @param url
	 *            跳转的URL
	 * @param falg
	 *            true 是成功 false 是失败
	 * @param redir
	 *            是否自动跳转 停留两秒钟
	 */
	@NotAction
	public void renderMsg(String title, String msg, String url, boolean falg, boolean redir) {
		setAttr("flag", new PageAlert(falg == true ? "OK" : "NO", title, msg, url, redir));
		render("/WEB-INF/weixin/common/alert.html");
	}

	// 设置错误的信息
	@NotAction
	public void error(String msg) {
		setAttr("error", msg);
	}

	/**
	 * 分页数据
	 * 
	 * @param data
	 */
	@NotAction
	public void paginate(Object data) {
		setAttr("data", data);
	}
	@NotAction
	public void success() {
		renderJson(new AjaxCmd(true));
	}
	@NotAction
	public void success(String msg) {
		renderJson(new AjaxCmd(true, msg));
	}
	@NotAction
	public void success(Object data) {
		renderJson(new AjaxCmd(data));
	}
	@NotAction
	public void fail() {
		renderJson(new AjaxCmd(false));
	}
	@NotAction
	public void fail(String msg) {
		renderJson(new AjaxCmd(false, msg));
	}
	@NotAction
	public void state(boolean state) {
		renderJson(new AjaxCmd(state));
	}

	/**
	 * 获取分页 页码
	 * 
	 * @return
	 */
	@NotAction
	public int getpage() {
		return getParaToInt("pageNumber", 1);
	}

	/**
	 * 获取分页 大小
	 * 
	 * @return
	 */
	@NotAction
	public int getpageSize() {
		return getParaToInt("pageSize", 10);
	}

	/**
	 * 从session 读取当前登录的用户
	 * 
	 * @return
	 */
	@NotAction
	public AdminUser getLogintUser() {
		return getSessionAttr(WebConst.Session_SysUser);
	}

	/**
	 * 判断是否是ajax
	 * 
	 * @return
	 */
	@NotAction
	public boolean isAjax() {
		String requtype = getRequest().getHeader("X-Requested-With");
		if (StringUtil.isNotBlank(requtype)) {
			if (requtype.equals("XMLHttpRequest")) {
				return true;
			}
		}
		return false;
	}

}
